/**
 * 
 */
package com.pmsco.pms.core.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.pmsco.pms.core.dao.MedicineDao;
import com.pmsco.pms.core.domain.Medicine;
import com.pmsco.pms.util.JQGridBuildWhereClause;

/**
 * @author Long Tran
 *
 */
public class MedicineDaoImpl extends HibernateDaoSupport implements MedicineDao {

	public Medicine saveOrUpdateMedicine(Medicine medicine) {
		medicine = getHibernateTemplate().merge(medicine);
		getHibernateTemplate().flush();
		return medicine;
	}

	public List<Medicine> listMedicine(Medicine searchTemplate) {
		List<Medicine> ret = new ArrayList<Medicine>();
		ret = getHibernateTemplate().findByExample(searchTemplate);
		return ret;
	}

	
	public Medicine loadMedicineById(Long id) {
		Medicine ret = null;
		ret = getHibernateTemplate().load(Medicine.class, id);
		return ret; 
	}
	
	public Medicine loadMedicine(Medicine searchTemplate) {
		Medicine ret = null;
		List<Medicine> temp = new ArrayList<Medicine>();
		temp = getHibernateTemplate().findByExample(searchTemplate);
		if(temp != null && temp.size() == 1)
			ret = temp.get(0);
		return ret; 
	}
	
	public void deleteMedicine(Medicine medicine) {
		getHibernateTemplate().delete(medicine);
		getHibernateTemplate().flush();
	}
	
	public List<Medicine> listMedicine(String searchField, String searchString, String searchOper, String sidx, String sord, Integer page, Integer rows) {
		List<Medicine> ret = new ArrayList<Medicine>();
		Criteria crit = this.getSession().createCriteria(Medicine.class);
		if(searchOper != null && searchOper.length() > 0)
			crit.add(JQGridBuildWhereClause.getWhereClase(searchField, searchString, searchOper));
		if("desc".equalsIgnoreCase(sord))
			crit.addOrder(Order.desc(sidx));
		else
			crit.addOrder(Order.asc(sidx));
		crit.setFirstResult((page - 1) * rows);
		crit.setMaxResults(page * rows);
		ret = crit.list();
		return ret;
	}
	
	public Integer countListMedicine(String searchField, String searchString, String searchOper) {
		Integer ret = new Integer(0);
		Criteria crit = this.getSession().createCriteria(Medicine.class);
		if(searchOper != null && searchOper.length() > 0)
			crit.add(JQGridBuildWhereClause.getWhereClase(searchField, searchString, searchOper));
		crit.setProjection(Projections.rowCount());
		ret = (Integer)crit.uniqueResult();
		return ret;
	}
}
